# !/usr/bin/env python
# -*- coding: utf-8 -*-
# @Time    : 2025/9/22 16:44
# @Author  : Dell
# @File    : angent.py
# @Software: PyCharm
# @Desc    : 构造一个查询天气agent
from langchain.agents import AgentExecutor, create_tool_calling_agent,tool
from langchain_core.prompts import ChatPromptTemplate
from langchain_openai import ChatOpenAI
import requests
# 前置准备：先去https://api.seniverse.com 网站申请api-key =SaoTEHUQlsMbJPCNZ
#1、定义一个天气查询函数工具

@tool
def get_weather(location:str) -> str:
    """
    获取天气函数
    :param location:
    :return:
    """
    url = "https://api.seniverse.com/v3/weather/now.json"
    params = {
        "key": "SaoTEHUQlsMbJPCNZ",
        "location": location,
        "language": "zh-Hans",
        "unit": "c",
    }
    # 发送请求并解析结果
    response = requests.get(url, params=params)
    data = response.json()
    # 从返回的 JSON 中提取关键天气信息
    if 'results' in data and len(data['results']) > 0:
        now = data['results'][0]['now']
        city_name = data['results'][0]['location']['name']
        weather_text = f"{city_name}当前天气：{now['text']}，温度：{now['temperature']}℃，更新时间：{data['results'][0]['last_update']}"
        return weather_text
    else:
        return f"未能查询到{location}的天气信息，请检查城市名称是否正确。"


# 2. 初始化大语言模型（这里使用 DeepSeek-V3 的兼容模式）
# 请替换为您的实际 API Key，并确保模型支持工具调用
llm = ChatOpenAI(model_name='qwen-plus', base_url="https://dashscope.aliyuncs.com/compatible-mode/v1", temperature=0.1,
                 api_key="sk-7b4f290b1a3e42a1a9a1957fa44eff37")

# 3. 定义工具列表
tools = [get_weather]
print(tools)
# 4. 创建提示模板
prompt = ChatPromptTemplate.from_messages([
    ("system","你是一个专业的天气查询助手。请根据用户的问题，智能地调用工具获取实时天气信息，并用友好、简洁的方式回复用户。"),
    ("human", "{input}"),
    ("placeholder", "{agent_scratchpad}"),  # 这是一个占位符，LangChain 会自动在此处填充 Agent 的思考和执行过程
])

# 5. 创建 Agent
agent = create_tool_calling_agent(llm, tools, prompt)

# 6. 创建 Agent 执行器
agent_executor = AgentExecutor(agent=agent, tools=tools, verbose=True)  # verbose=True 会打印详细执行过程

# 7. 运行 Agent
if __name__ == "__main__":
    try:
        result = agent_executor.invoke("今天北京的天气怎么样？")
        # print(result["output"])
    except Exception as e:
        print(f"执行出错: {e}")